package com.swing.gui.component;

import com.swing.gui.APP;
import com.swing.thread.TrayFlash;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * @author Yuang, Gongming
 * @date 2022-01-14 11:08
 */
public class MiniTray {
    private static TrayIcon trayIcon;
    public static long x;
    public static long y;

    private MiniTray() {
        //  禁止托盘实例化，主窗体构建完毕后生成一次！
    }

    public static TrayIcon init() {
        Image iconImage = APP.init().getIconImage();
        if (trayIcon == null) {
            synchronized (TrayIcon.class) {
                if (trayIcon == null) {
                    trayIcon = new TrayIcon(iconImage);
                    template();
                    listener();
                }
            }
        } else {
            trayIcon.setImage(iconImage);
        }

        try {
            SystemTray.getSystemTray().add(trayIcon);
        } catch (Exception e) {
            //  ignore……
        }
        return trayIcon;
    }

    /**
     * 初始化模板
     */
    private static void template() {
        trayIcon.setToolTip(APP.init().getTitle());
        trayIcon.setImageAutoSize(true);
    }

    private static void listener() {
        trayIcon.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {

                //  鼠标右键
                if (MouseEvent.BUTTON3 == e.getButton()) {
                    x = e.getX();
                    y = e.getY();

                    System.out.println("托盘右击" + System.currentTimeMillis());

                    MiniPopup.init();

                }

                //  鼠标左键
                if (MouseEvent.BUTTON1 == e.getButton()) {
                    TrayFlash.init(false);

                    //  fixme - 暂停托盘消失
//                    SystemTray.getSystemTray().remove(trayIcon);
                    APP.init().setVisible(true);
                    APP.init().setExtendedState(JFrame.NORMAL);
                    APP.init().toFront();
                }

                //  鼠标滑轮，忽略

            }

        });

    }

}
